<!--
 * @author dumeng
 自定义页面版本管理
 -->
<template>
  <div class="page-version-page">
    <div class="btn-container">
      <div class="btn-container-title">
        <span>页面版本管理</span>
      </div>
      <div class="btn-container-btns">
        <el-button
          class="filter-item"
          style="margin-left: 10px"
          @click="handleCancel"
        >返回</el-button>
      </div>
    </div>
    <section class="main-table">
      <v-table
        :list="list"
        tag="pageManageVersionList"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
      >
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="handleConfig(scope.row)"
            >还原</el-button>
            <el-button
              type="text"
              size="mini"
              @click="view(scope.row)"
            >预览</el-button>
            <!-- <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </v-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </section>
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      title="选择生效时间"
      :visible.sync="publishVisible"
      center
      width="450px"
    >
      <el-date-picker
        v-model="effectTime"
        style="width: 100%"
        type="datetime"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        placeholder="请选择"
      />
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="publishVisible = false"
        >取消</el-button>
        <el-button
          style="padding: 8px 30px"
          type="primary"
          @click="publish"
        >确定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="visible4init"
      title="设置初始值"
      center
      :before-close="
        () => {
          visible4init = false;
        }
      "
    >
      <el-form ref="form" :model="varForm" label-width="140px">
        <el-form-item v-for="(item, index) in varList" :key="item + index" :label="varList[index].name">
          <el-input v-model="varForm[item.code]" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          style="padding: 8px 30px"
          @click="visible4init = false"
        >关 闭</el-button>
        <el-button
          type="primary"
          style="padding: 8px 30px"
          @click="handleVarSubmit"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { queryPage, del, publish, getDictByCode } from '../api/version'
import VTable from '@/components/Table'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
import elDragDialog from '@/directive/el-drag-dialog'
// eslint-disable-next-line no-unused-vars

export default {
  name: 'PageIndex',
  components: { VTable, Pagination },
  directives: { permission, elDragDialog },
  data() {
    return {
      id: '',
      listQuery: {
        page: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      multipleSelection: [],
      listLoading: false,
      publishVisible: false,
      recordId: '',
      effectTime: '',
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() // 选当前时间之后的时间
        }
      },
      curPreview: {},
      ZDYYMBL: [],
      varList: [],
      visible4init: false,
      varForm: {}
    }
  },
  created() {
    if (this.$route.query.i) {
      this.id = this.$route.query.i
      this.getList()
    } else {
      this.$message({
        showClose: true,
        message: '参数异常！',
        type: 'warning',
        onClose: () => {
          this.handleCancel()
        }
      })
    }
  },
  methods: {
    // 获取字典
    getDict() {
      return new Promise((resolve, reject) => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        getDictByCode('ZDYYMBL')
          .then((res) => {
            loading.close()
            this.ZDYYMBL =
              res.data.data && res.data.data.length > 0
                ? res.data.data[0].list
                : []
            resolve()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    getVarLabel(value) {
      const target = this.ZDYYMBL.find((item) => {
        return item.dictValue === value
      })
      return Object.keys(target).length ? target.dictName : ''
    },
    async view(item) {
      if (!item.config) {
        this.$message({
          message: '页面配置为空',
          type: 'warning'
        })
        return
      }
      try {
        this.curPreview = JSON.parse(item.config)
      } catch (err) {
        this.$message({
          message: '页面配置有误，请重新配置。',
          type: 'warning'
        })
        return
      }
      this.varList = this.curPreview.pageVar || []
      if (this.varList.length) {
        this.varList.forEach(item => {
          this.$set(this.varForm, item.code, item.value)
        })
        this.visible4init = true
      } else {
        this.preview()
      }
    },
    handleVarSubmit() {
      if (
        Object.values(this.varForm).some((item) => {
          return item
        })
      ) {
        this.visible4init = false
        this.preview()
      } else {
        this.$message({
          message: '初始信息不能为空',
          type: 'warning'
        })
      }
    },
    async preview() {
      const { default: DialogView } = await import(
        '@/components/CustomPage/pagemaker/view'
      )
      this.$modal.show(
        DialogView,
        {
          title: '预览',
          inner: this.curPreview,
          varInfo: this.varForm,
          fn: this.handleComit,
          isInitData: true
        },
        {
          width: 600,
          height: 'auto',
          clickToClose: false
        }
      )
    },
    filtercolumn(scope, item) {
      if (item === 'isKeepAlive') {
        return scope.row[item] === '0' ? '是' : '否'
      } else {
        return scope.row[item]
      }
    },
    /**
     * 选择生效时间后发布
     */
    publish() {
      this.$confirm('确认还原？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        publish({
          id: this.id,
          recordId: this.recordId,
          effectTime: this.effectTime
        })
          .then((res) => {
            if (res.data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })

              loading.close()
              this.publishVisible = false
            }
          })
          .catch(() => {
            loading.close()
          })
      })
    },
    handleCancel() {
      this.$router.replace({ path: '/pagemanage/index', query: { s: 2 }})
    },
    getList(obj) {
      var query = {
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.pageSize,
        id: this.id
      }
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(query)
          .then((res) => {
            this.listLoading = false
            this.list = res.data.data.rows || []
            this.total = res.data.data.total
          })
          .catch((error) => {
            reject(error)
            this.listLoading = false
          })
      })
    },
    handleConfig(rwo) {
      this.$router.push(`/pagemanage/config?i=${rwo.id}&id=${rwo.id}`)
    },
    handleRevert(rwo) {
      this.recordId = rwo.id
      this.publishVisible = true
    },
    /**
     * 预览
     * @param row
     */
    handleView(row) {},
    handleDeletes() {
      const arr = []
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item) => {
          arr.push(item.id)
        })
        const ids = arr.join(',')
        this.deleteUser(ids)
      } else {
        this.$message({
          message: '请选择需要删除的数据！',
          type: 'warning'
        })
      }
    },
    handleDelete(row) {
      this.deleteUser(row.id)
    },
    deleteUser(ids) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del({ ids: ids }).then((res) => {
            this.$message.success('删除成功!')
            this.getList()
          })
        })
        .catch(() => {})
    },
    handleSelectionChange(arr) {
      this.multipleSelection = arr
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
// $mainColor: #18a5fd;
.page-version-page {
  padding: 10px 20px 10px 10px;
  .btn-container {
    display: flex;
    align-items: center;
    margin-top: 5px;
    margin-bottom: 5px;
    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
    }
  }
}
</style>
